import { routerArrays } from '@/layout/types'
import { isEqual, isUrl, storageLocal } from '@pureadmin/utils'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { MultiTabItem } from './types'
import { isEmpty } from 'lodash-es'

function getTabCacheConfigure() {
  return storageLocal().getItem<StorageConfigs>('responsive-configure')?.multiTabsCache
}

function getTabCache() {
  return storageLocal().getItem<Array<MultiTabItem>>('responsive-tags')
}

function setTabCache(data: Array<MultiTabItem>) {
  storageLocal().setItem('responsive-tags', data)
}

function removeTabCache() {
  storageLocal().removeItem('responsive-tags')
}

export const useMultiTabStore = defineStore('pure-multi-tabs', () => {
  const tabs = ref<Array<MultiTabItem>>(getTabCacheConfigure() ? getTabCache() : [...routerArrays])
  const enableMultiTabsCache = ref(getTabCacheConfigure())

  function toggleMultiTagsCache(value: boolean) {
    enableMultiTabsCache.value = value
    if (value) {
      setTabCache(tabs.value)
    } else {
      removeTabCache()
    }
  }

  function pushTab(value: MultiTabItem) {
    const newTag = value

    if (
      newTag.meta?.hiddenTag || //配置了 hiddenTag 的路由不添加标签
      isUrl(newTag?.name) || // 如果是外链无需添加信息到标签页
      isEmpty(newTag?.meta?.title) // 如果 title 为空不添加标签
    ) {
      return
    }

    const path = newTag.path
    // 判断tag是否已存在
    const isTagExits = tabs.value.some(
      (tag) =>
        tag.path === path &&
        isEqual(tag?.query, newTag?.query) &&
        isEqual(tag?.params, newTag?.params)
    )
    if (isTagExits) return

    // 动态路由可打开的最大数量
    const dynamicLevel = newTag?.meta?.dynamicLevel ?? -1
    if (dynamicLevel > 0) {
      if (tabs.value.filter((e) => e?.path === path).length >= dynamicLevel) {
        // 如果当前已打开的动态路由数大于dynamicLevel，替换第一个动态路由标签
        const index = tabs.value.findIndex((item) => item?.path === path)
        index !== -1 && tabs.value.splice(index, 1)
      }
    }
    tabs.value.push(value)
    setTabCache(tabs.value)
  }

  function setTabs(values: Array<MultiTabItem>) {
    tabs.value = values
    setTabCache(tabs.value)
  }

  function removeTabs(from: number, count: number) {
    tabs.value.splice(from, count)
    setTabCache(tabs.value)
  }

  function getLatestTab() {
    return tabs.value.slice(-1)
  }

  return {
    tabs,
    enableMultiTabsCache,
    getLatestTab,
    setTabs,
    pushTab,
    removeTabs,
    toggleMultiTagsCache,
  }
})
